// 面试辅导系统 - 精简版脚本

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 应用初始化
function initializeApp() {
    // 初始化主题系统
    initializeTheme();
    
    // 设置导航菜单高亮
    setActiveNavigation();
    
    // 初始化搜索功能
    initializeSearch();
    
    // 初始化用户菜单
    initializeUserMenu();
    
    // 根据页面类型初始化特定功能
    const pageName = getPageName();
    switch(pageName) {
        case 'index':
            initializeDashboard();
            break;
        case 'resume':
            initializeResumeEditor();
            break;
        case 'interview':
            initializeInterviewSimulator();
            break;
        case 'profile':
            initializeProfile();
            break;
    }
}

// 获取当前页面名称
function getPageName() {
    const path = window.location.pathname;
    const fileName = path.split('/').pop().split('.')[0];
    return fileName === '' ? 'index' : fileName;
}

// 设置导航菜单高亮
function setActiveNavigation() {
    const currentPage = getPageName();
    const navLinks = document.querySelectorAll('.navbar-nav a');
    
    navLinks.forEach(link => {
        const href = link.getAttribute('href');
        const linkPage = href.split('/').pop().split('.')[0];
        
        if (linkPage === currentPage || (currentPage === 'index' && href === '/')) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });
}

// 初始化搜索功能
function initializeSearch() {
    const searchInput = document.querySelector('.search-input');
    if (searchInput) {
        searchInput.addEventListener('input', handleSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch(this.value);
            }
        });
    }
}

// 处理搜索
function handleSearch(e) {
    const query = e.target.value.trim();
    if (query.length > 2) {
        // 这里可以添加实时搜索建议功能
        console.log('搜索:', query);
    }
}

// 执行搜索
function performSearch(query) {
    if (query.trim()) {
        console.log('执行搜索:', query);
        // 这里可以实现搜索跳转或显示搜索结果
    }
}

// 初始化用户菜单
function initializeUserMenu() {
    const userAvatar = document.querySelector('.user-avatar');
    if (userAvatar) {
        userAvatar.addEventListener('click', toggleUserMenu);
    }
}

// 切换用户菜单
function toggleUserMenu() {
    console.log('切换用户菜单');
    // 这里可以实现用户下拉菜单
}

// 首页仪表板初始化
function initializeDashboard() {
    // 初始化统计数据动画
    animateStatsCards();
    
    // 初始化快捷操作卡片点击事件
    initializeActionCards();
    
    // 模拟数据加载
    loadDashboardData();
}

// 统计卡片动画
function animateStatsCards() {
    const statsNumbers = document.querySelectorAll('.stats-number');
    statsNumbers.forEach((element, index) => {
        setTimeout(() => {
            element.style.opacity = '0';
            element.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                element.style.transition = 'all 0.5s ease-out';
                element.style.opacity = '1';
                element.style.transform = 'translateY(0)';
            }, 100);
        }, index * 150);
    });
}

// 初始化快捷操作卡片
function initializeActionCards() {
    const actionCards = document.querySelectorAll('.action-card');
    actionCards.forEach(card => {
        card.addEventListener('click', function() {
            const action = this.dataset.action;
            handleActionCardClick(action);
        });
    });
}

// 处理快捷操作卡片点击
function handleActionCardClick(action) {
    switch(action) {
        case 'resume':
            window.location.href = 'resume.html';
            break;
        case 'interview':
            window.location.href = 'interview.html';
            break;
        default:
            console.log('未知操作:', action);
    }
}

// 处理操作卡片点击（新版本）
function handleActionClick(action) {
    switch(action) {
        case 'resume':
            window.location.href = 'resume.html';
            break;
        case 'interview':
            window.location.href = 'interview.html';
            break;
        case 'export':
            window.location.href = 'resume.html';
            break;
        default:
            showMessage('功能开发中', 'info');
    }
}

// 加载仪表板数据
function loadDashboardData() {
    // 模拟API调用
    setTimeout(() => {
        updateRecentRecords();
    }, 1000);
}

// 更新最近记录
function updateRecentRecords() {
    const recordList = document.querySelector('.record-list');
    if (recordList) {
        // 这里可以动态更新记录列表
        console.log('更新最近记录');
    }
}

// 简历编辑器初始化
function initializeResumeEditor() {
    // 初始化表单验证
    initializeFormValidation();
    
    // 初始化编辑功能
    initializeEditingFeatures();
    
    // 初始化预览更新
    initializePreviewUpdate();
    
    // 初始化模板系统
    initializeTemplateSystem();
    
    // 初始化AI分析
    initializeAIAnalysis();
    
    // 初始化PDF导出
    initializePDFExport();
    
    // 加载简历数据
    loadResumeData();
    
    // 初始更新预览
    updatePreview();
}

// 初始化表单验证
function initializeFormValidation() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', handleFormSubmit);
        
        const inputs = form.querySelectorAll('.form-input');
        inputs.forEach(input => {
            input.addEventListener('blur', validateField);
            input.addEventListener('input', clearFieldError);
        });
    });
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    const form = e.target;
    
    if (validateForm(form)) {
        saveResumeData(form);
    }
}

// 验证表单
function validateForm(form) {
    let isValid = true;
    const inputs = form.querySelectorAll('.form-input[required]');
    
    inputs.forEach(input => {
        if (!validateField({ target: input })) {
            isValid = false;
        }
    });
    
    return isValid;
}

// 验证字段
function validateField(e) {
    const input = e.target;
    const value = input.value.trim();
    let isValid = true;
    
    // 必填验证
    if (input.hasAttribute('required') && !value) {
        showFieldError(input, '此字段为必填项');
        isValid = false;
    }
    // 邮箱验证
    else if (input.type === 'email' && value && !isValidEmail(value)) {
        showFieldError(input, '请输入有效的邮箱地址');
        isValid = false;
    }
    // 手机号验证
    else if (input.type === 'tel' && value && !isValidPhone(value)) {
        showFieldError(input, '请输入有效的手机号码');
        isValid = false;
    }
    
    return isValid;
}

// 显示字段错误
function showFieldError(input, message) {
    input.classList.add('error');
    
    // 移除现有错误信息
    const existingError = input.parentNode.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }
    
    // 添加错误信息
    const errorElement = document.createElement('div');
    errorElement.className = 'error-message';
    errorElement.style.color = 'var(--error-color)';
    errorElement.style.fontSize = 'var(--font-size-sm)';
    errorElement.style.marginTop = 'var(--spacing-xs)';
    errorElement.textContent = message;
    
    input.parentNode.appendChild(errorElement);
}

// 清除字段错误
function clearFieldError(e) {
    const input = e.target;
    input.classList.remove('error');
    
    const errorMessage = input.parentNode.querySelector('.error-message');
    if (errorMessage) {
        errorMessage.remove();
    }
}

// 邮箱验证
function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// 手机号验证
function isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
}

// 初始化编辑功能
function initializeEditingFeatures() {
    // 添加经历按钮
    const addButtons = document.querySelectorAll('[data-action="add"]');
    addButtons.forEach(button => {
        button.addEventListener('click', handleAddItem);
    });
    
    // 删除按钮
    document.addEventListener('click', function(e) {
        if (e.target.dataset.action === 'delete') {
            handleDeleteItem(e);
        }
    });
}

// 处理添加项目
function handleAddItem(e) {
    const button = e.target;
    const type = button.dataset.type;
    
    switch(type) {
        case 'experience':
            addWorkExperience();
            break;
        case 'project':
            addProject();
            break;
        case 'education':
            addEducation();
            break;
    }
}

// 添加工作经历
function addWorkExperience() {
    const container = document.querySelector('#work-experience-list');
    if (container) {
        const item = createExperienceItem();
        container.appendChild(item);
        updatePreview();
    }
}

// 创建经历项目
function createExperienceItem() {
    const div = document.createElement('div');
    div.className = 'experience-item';
    div.innerHTML = `
        <div class="grid grid-2">
            <div class="form-group">
                <label class="form-label">公司名称</label>
                <input type="text" class="form-input" name="company" required>
            </div>
            <div class="form-group">
                <label class="form-label">职位</label>
                <input type="text" class="form-input" name="position" required>
            </div>
        </div>
        
        <div class="grid grid-2">
            <div class="form-group">
                <label class="form-label">开始时间</label>
                <input type="month" class="form-input" name="start_date">
            </div>
            <div class="form-group">
                <label class="form-label">结束时间</label>
                <input type="month" class="form-input" name="end_date">
            </div>
        </div>
        
        <div class="form-group">
            <label class="form-label">工作描述</label>
            <textarea class="form-input" name="description" rows="3" placeholder="请描述您的主要工作内容和取得的成果..."></textarea>
        </div>
        
        <button type="button" class="btn btn-text" data-action="delete" style="color: var(--error-color);">删除</button>
    `;
    
    // 为新添加的输入框绑定事件
    div.querySelectorAll('.form-input').forEach(input => {
        input.addEventListener('input', debounce(updatePreview, 300));
        input.addEventListener('blur', validateField);
        input.addEventListener('input', clearFieldError);
    });
    
    return div;
}

// 添加项目经验
function addProject() {
    const container = document.querySelector('#project-list');
    if (container) {
        const item = createProjectItem();
        container.appendChild(item);
        updatePreview();
    }
}

// 创建项目项目
function createProjectItem() {
    const div = document.createElement('div');
    div.className = 'project-item';
    div.innerHTML = `
        <div class="form-group">
            <label class="form-label">项目名称</label>
            <input type="text" class="form-input" name="project_name" required>
        </div>
        
        <div class="grid grid-2">
            <div class="form-group">
                <label class="form-label">项目时间</label>
                <input type="text" class="form-input" name="project_time" placeholder="如：2022.01-2023.12">
            </div>
            <div class="form-group">
                <label class="form-label">项目角色</label>
                <input type="text" class="form-input" name="project_role" placeholder="如：核心开发">
            </div>
        </div>
        
        <div class="form-group">
            <label class="form-label">技术栈</label>
            <input type="text" class="form-input" name="tech_stack" placeholder="如：Spring Boot, Redis, MySQL">
        </div>
        
        <div class="form-group">
            <label class="form-label">项目描述</label>
            <textarea class="form-input" name="project_desc" rows="3" placeholder="请描述项目的主要功能和您的贡献..."></textarea>
        </div>
        
        <button type="button" class="btn btn-text" data-action="delete" style="color: var(--error-color);">删除</button>
    `;
    
    // 为新添加的输入框绑定事件
    div.querySelectorAll('.form-input').forEach(input => {
        input.addEventListener('input', debounce(updatePreview, 300));
        input.addEventListener('blur', validateField);
        input.addEventListener('input', clearFieldError);
    });
    
    return div;
}

// 添加教育背景
function addEducation() {
    showMessage('教育背景功能开发中', 'info');
}

// 处理删除项目
function handleDeleteItem(e) {
    if (confirm('确定要删除这个项目吗？')) {
        const item = e.target.closest('.experience-item, .project-item, .education-item');
        if (item) {
            item.remove();
            updatePreview();
        }
    }
}

// 初始化预览更新
function initializePreviewUpdate() {
    const inputs = document.querySelectorAll('.form-input');
    inputs.forEach(input => {
        input.addEventListener('input', debounce(updatePreview, 300));
    });
}

// 更新预览
function updatePreview() {
    const form = document.getElementById('resume-form');
    const preview = document.getElementById('resume-preview');
    
    if (!form || !preview) return;
    
    const formData = new FormData(form);
    const data = {};
    
    // 收集表单数据
    for (let [key, value] of formData.entries()) {
        if (data[key]) {
            if (Array.isArray(data[key])) {
                data[key].push(value);
            } else {
                data[key] = [data[key], value];
            }
        } else {
            data[key] = value;
        }
    }
    
    // 收集工作经历
    const experiences = [];
    const experienceItems = document.querySelectorAll('.experience-item');
    experienceItems.forEach(item => {
        const exp = {
            company: item.querySelector('[name="company"]')?.value || '',
            position: item.querySelector('[name="position"]')?.value || '',
            startDate: item.querySelector('[name="start_date"]')?.value || '',
            endDate: item.querySelector('[name="end_date"]')?.value || '',
            description: item.querySelector('[name="description"]')?.value || ''
        };
        if (exp.company && exp.position) {
            experiences.push(exp);
        }
    });
    
    // 收集项目经验
    const projects = [];
    const projectItems = document.querySelectorAll('.project-item');
    projectItems.forEach(item => {
        const project = {
            name: item.querySelector('[name="project_name"]')?.value || '',
            time: item.querySelector('[name="project_time"]')?.value || '',
            role: item.querySelector('[name="project_role"]')?.value || '',
            techStack: item.querySelector('[name="tech_stack"]')?.value || '',
            description: item.querySelector('[name="project_desc"]')?.value || ''
        };
        if (project.name) {
            projects.push(project);
        }
    });
    
    // 更新预览内容
    updatePreviewContent({
        name: data.name || '姓名',
        position: data.position || '求职意向',
        phone: data.phone || '手机号',
        email: data.email || '邮箱',
        summary: data.summary || '个人简介',
        school: data.school || '学校',
        major: data.major || '专业',
        degree: data.degree || '学历',
        graduation: data.graduation || '毕业时间',
        skills: data.skills || '技能专长',
        experiences: experiences,
        projects: projects
    });
    
    // 触发AI分析
    performAIAnalysis(data, experiences, projects);
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 加载简历数据
function loadResumeData() {
    // 模拟从本地存储或API加载数据
    const savedData = localStorage.getItem('resumeData');
    if (savedData) {
        const data = JSON.parse(savedData);
        populateForm(data);
    }
}

// 填充表单数据
function populateForm(data) {
    Object.keys(data).forEach(key => {
        const input = document.querySelector(`[name="${key}"]`);
        if (input) {
            input.value = data[key];
        }
    });
    updatePreview();
}

// 保存简历数据
function saveResumeData(form) {
    const formData = new FormData(form);
    const data = {};
    
    for (let [key, value] of formData.entries()) {
        data[key] = value;
    }
    
    localStorage.setItem('resumeData', JSON.stringify(data));
    showMessage('简历已保存', 'success');
}

// 面试模拟器初始化
function initializeInterviewSimulator() {
    // 初始化聊天界面
    initializeChatInterface();
    
    // 初始化语音功能
    initializeVoiceFeatures();
    
    // 开始面试
    startInterview();
}

// 初始化聊天界面
function initializeChatInterface() {
    const chatInput = document.querySelector('.chat-input');
    const sendButton = document.querySelector('#send-message');
    
    if (chatInput) {
        chatInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    }
    
    if (sendButton) {
        sendButton.addEventListener('click', sendMessage);
    }
}

// 发送消息
function sendMessage() {
    const chatInput = document.querySelector('.chat-input');
    const message = chatInput.value.trim();
    
    if (message) {
        addMessage(message, 'user');
        chatInput.value = '';
        
        // 模拟AI回复
        setTimeout(() => {
            generateAIResponse(message);
        }, 1000);
    }
}

// 添加消息到聊天界面
function addMessage(content, sender) {
    const messagesContainer = document.querySelector('.chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}`;
    
    messageDiv.innerHTML = `
        <div class="message-avatar">${sender === 'user' ? '👤' : '🤖'}</div>
        <div class="message-content">${content}</div>
    `;
    
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// 生成AI回复
function generateAIResponse(userMessage) {
    // 模拟AI回复逻辑
    const responses = [
        '很好，能详细说说具体的技术实现吗？',
        '这个项目中遇到了什么困难？你是如何解决的？',
        '你觉得这个经历对你最大的收获是什么？',
        '在团队协作中，你扮演了什么角色？'
    ];
    
    const randomResponse = responses[Math.floor(Math.random() * responses.length)];
    addMessage(randomResponse, 'bot');
    
    // 显示反馈提示
    showFeedbackTip();
}

// 显示反馈提示
function showFeedbackTip() {
    const feedbackTip = document.createElement('div');
    feedbackTip.className = 'feedback-tip';
    feedbackTip.textContent = '💡 本题得分: 78分 | 建议: 可以补充具体的解决方案';
    
    const inputArea = document.querySelector('.chat-input-area');
    inputArea.insertBefore(feedbackTip, inputArea.firstChild);
    
    // 3秒后自动移除
    setTimeout(() => {
        feedbackTip.remove();
    }, 3000);
}

// 初始化语音功能
function initializeVoiceFeatures() {
    const voiceButton = document.querySelector('#voice-input');
    if (voiceButton) {
        voiceButton.addEventListener('click', toggleVoiceInput);
    }
}

// 切换语音输入
function toggleVoiceInput() {
    console.log('切换语音输入');
    // 这里可以实现语音识别功能
}

// 开始面试
function startInterview() {
    setTimeout(() => {
        addMessage('您好！欢迎来到面试模拟，我是面试官李总监。请先做一个简单的自我介绍吧。', 'bot');
    }, 500);
}

// 个人中心初始化
function initializeProfile() {
    // 初始化编辑功能
    initializeProfileEditing();
    
    // 初始化统计图表
    initializeStatsCharts();
    
    // 加载个人数据
    loadProfileData();
}

// 初始化个人资料编辑
function initializeProfileEditing() {
    const editButtons = document.querySelectorAll('[data-action="edit"]');
    editButtons.forEach(button => {
        button.addEventListener('click', enableEditing);
    });
}

// 启用编辑模式
function enableEditing(e) {
    const section = e.target.closest('.info-card');
    const fields = section.querySelectorAll('.info-value');
    
    fields.forEach(field => {
        const currentValue = field.textContent;
        const input = document.createElement('input');
        input.type = 'text';
        input.value = currentValue;
        input.className = 'form-input';
        
        field.parentNode.replaceChild(input, field);
    });
    
    // 更换按钮为保存/取消
    e.target.textContent = '保存';
    e.target.dataset.action = 'save';
}

// 初始化统计图表
function initializeStatsCharts() {
    // 这里可以初始化图表库，如Chart.js
    console.log('初始化统计图表');
}

// 加载个人数据
function loadProfileData() {
    // 模拟数据加载
    console.log('加载个人数据');
}

// 显示消息提示
function showMessage(message, type = 'info') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message-toast message-${type}`;
    messageDiv.textContent = message;
    
    // 样式
    messageDiv.style.cssText = `
        position: fixed;
        top: 80px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 6px;
        color: white;
        font-weight: 500;
        z-index: 2000;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease-out;
    `;
    
    // 根据类型设置背景色
    switch(type) {
        case 'success':
            messageDiv.style.backgroundColor = 'var(--success-color)';
            break;
        case 'error':
            messageDiv.style.backgroundColor = 'var(--error-color)';
            break;
        case 'warning':
            messageDiv.style.backgroundColor = 'var(--warning-color)';
            break;
        default:
            messageDiv.style.backgroundColor = 'var(--primary-color)';
    }
    
    document.body.appendChild(messageDiv);
    
    // 显示动画
    requestAnimationFrame(() => {
        messageDiv.style.opacity = '1';
        messageDiv.style.transform = 'translateX(0)';
    });
    
    // 3秒后自动移除
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        messageDiv.style.transform = 'translateX(100%)';
        
        setTimeout(() => {
            document.body.removeChild(messageDiv);
        }, 300);
    }, 3000);
}

// 更新预览内容
function updatePreviewContent(data) {
    const preview = document.getElementById('resume-preview');
    if (!preview) return;
    
    const currentTemplate = localStorage.getItem('selectedTemplate') || 'modern';
    
    switch(currentTemplate) {
        case 'classic':
            preview.innerHTML = generateClassicTemplate(data);
            break;
        case 'tech':
            preview.innerHTML = generateTechTemplate(data);
            break;
        default:
            preview.innerHTML = generateModernTemplate(data);
    }
}

// 现代简约模板
function generateModernTemplate(data) {
    return `
        <div style="text-align: center; margin-bottom: 24px; border-bottom: 2px solid var(--primary-color); padding-bottom: 16px;">
            <h1 style="margin: 0 0 8px 0; color: var(--primary-color); font-size: 28px;">${data.name}</h1>
            <div style="color: var(--gray-500); font-size: 16px; margin-bottom: 8px;">${data.position}</div>
            <div style="color: var(--gray-500); font-size: 14px;">
                📱 ${data.phone} | 📧 ${data.email}
            </div>
        </div>

        ${data.summary ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px;">个人简介</h3>
            <p style="margin: 0; color: var(--gray-900); line-height: 1.6;">${data.summary}</p>
        </div>
        ` : ''}

        ${data.experiences.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px;">工作经历</h3>
            ${data.experiences.map(exp => `
                <div style="margin-bottom: 16px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                        <strong>${exp.position} - ${exp.company}</strong>
                        <span style="color: var(--gray-500);">${exp.startDate} - ${exp.endDate}</span>
                    </div>
                    <p style="margin: 0; color: var(--gray-900); line-height: 1.6;">${exp.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        ${data.projects.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px;">项目经验</h3>
            ${data.projects.map(project => `
                <div style="margin-bottom: 16px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                        <strong>${project.name}</strong>
                        <span style="color: var(--gray-500);">${project.time}</span>
                    </div>
                    <div style="margin-bottom: 4px; color: var(--gray-500); font-size: 14px;">
                        技术栈: ${project.techStack} | 角色: ${project.role}
                    </div>
                    <p style="margin: 0; color: var(--gray-900); line-height: 1.6;">${project.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px;">教育背景</h3>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <strong>${data.school}</strong>
                    <span style="color: var(--gray-500); margin-left: 8px;">${data.degree} | ${data.major}</span>
                </div>
                <span style="color: var(--gray-500);">${data.graduation}毕业</span>
            </div>
        </div>

        ${data.skills ? `
        <div>
            <h3 style="color: var(--primary-color); margin-bottom: 8px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px;">技能专长</h3>
            <div style="color: var(--gray-900); white-space: pre-line; line-height: 1.6;">${data.skills}</div>
        </div>
        ` : ''}
    `;
}

// 商务经典模板
function generateClassicTemplate(data) {
    return `
        <div style="border-bottom: 3px solid #1a365d; padding-bottom: 16px; margin-bottom: 24px;">
            <h1 style="margin: 0; color: #1a365d; font-size: 32px; font-weight: bold;">${data.name}</h1>
            <div style="color: #4a5568; font-size: 18px; margin-top: 4px;">${data.position}</div>
            <div style="color: #718096; margin-top: 8px; font-size: 14px;">
                ${data.phone} • ${data.email}
            </div>
        </div>

        ${data.summary ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: #1a365d; font-size: 16px; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;">PROFILE</h3>
            <p style="margin: 0; color: #2d3748; line-height: 1.7; text-align: justify;">${data.summary}</p>
        </div>
        ` : ''}

        ${data.experiences.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: #1a365d; font-size: 16px; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px;">EXPERIENCE</h3>
            ${data.experiences.map(exp => `
                <div style="margin-bottom: 20px; border-left: 3px solid #e2e8f0; padding-left: 16px;">
                    <div style="margin-bottom: 4px;">
                        <strong style="color: #1a365d; font-size: 16px;">${exp.position}</strong>
                        <span style="color: #4a5568; margin-left: 8px;">${exp.company}</span>
                    </div>
                    <div style="color: #718096; font-size: 14px; margin-bottom: 8px;">${exp.startDate} - ${exp.endDate}</div>
                    <p style="margin: 0; color: #2d3748; line-height: 1.6;">${exp.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        ${data.projects.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: #1a365d; font-size: 16px; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px;">PROJECTS</h3>
            ${data.projects.map(project => `
                <div style="margin-bottom: 20px; border-left: 3px solid #e2e8f0; padding-left: 16px;">
                    <div style="margin-bottom: 4px;">
                        <strong style="color: #1a365d; font-size: 16px;">${project.name}</strong>
                        <span style="color: #718096; margin-left: 8px;">${project.time}</span>
                    </div>
                    <div style="color: #4a5568; font-size: 14px; margin-bottom: 8px;">
                        ${project.techStack} | ${project.role}
                    </div>
                    <p style="margin: 0; color: #2d3748; line-height: 1.6;">${project.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
            <div>
                <h3 style="color: #1a365d; font-size: 16px; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;">EDUCATION</h3>
                <div style="border-left: 3px solid #e2e8f0; padding-left: 16px;">
                    <strong style="color: #1a365d;">${data.school}</strong>
                    <div style="color: #4a5568; margin-top: 2px;">${data.degree} in ${data.major}</div>
                    <div style="color: #718096; font-size: 14px; margin-top: 2px;">${data.graduation}</div>
                </div>
            </div>
            <div>
                <h3 style="color: #1a365d; font-size: 16px; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;">SKILLS</h3>
                <div style="color: #2d3748; white-space: pre-line; line-height: 1.6; font-size: 14px;">${data.skills}</div>
            </div>
        </div>
    `;
}

// 专业技术模板
function generateTechTemplate(data) {
    return `
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 24px; margin: -24px -24px 24px -24px; border-radius: 6px 6px 0 0;">
            <h1 style="margin: 0; font-size: 28px; font-weight: 700;">${data.name}</h1>
            <div style="font-size: 16px; margin-top: 8px; opacity: 0.9;">${data.position}</div>
            <div style="margin-top: 12px; opacity: 0.8; font-size: 14px;">
                📱 ${data.phone} | 📧 ${data.email}
            </div>
        </div>

        ${data.summary ? `
        <div style="margin-bottom: 24px; background: #f8fafc; padding: 16px; border-radius: 6px; border-left: 4px solid var(--primary-color);">
            <h3 style="color: var(--primary-color); margin-bottom: 8px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">// ABOUT</h3>
            <p style="margin: 0; color: #2d3748; line-height: 1.6; font-family: 'Courier New', monospace;">${data.summary}</p>
        </div>
        ` : ''}

        ${data.experiences.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 12px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">// EXPERIENCE</h3>
            ${data.experiences.map((exp, index) => `
                <div style="margin-bottom: 16px; background: #f8fafc; padding: 16px; border-radius: 6px; position: relative;">
                    <div style="position: absolute; left: 0; top: 0; bottom: 0; width: 4px; background: ${index % 2 === 0 ? '#667eea' : '#764ba2'};"></div>
                    <div style="margin-bottom: 4px;">
                        <code style="color: var(--primary-color); font-weight: bold;">${exp.position}</code>
                        <span style="color: #4a5568; margin-left: 8px;">@ ${exp.company}</span>
                    </div>
                    <div style="color: #718096; font-size: 12px; margin-bottom: 8px; font-family: 'Courier New', monospace;">${exp.startDate} → ${exp.endDate}</div>
                    <p style="margin: 0; color: #2d3748; line-height: 1.6; font-size: 14px;">${exp.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        ${data.projects.length > 0 ? `
        <div style="margin-bottom: 24px;">
            <h3 style="color: var(--primary-color); margin-bottom: 12px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">// PROJECTS</h3>
            ${data.projects.map((project, index) => `
                <div style="margin-bottom: 16px; background: #f8fafc; padding: 16px; border-radius: 6px; border: 1px solid #e2e8f0;">
                    <div style="margin-bottom: 4px;">
                        <code style="color: var(--primary-color); font-weight: bold; font-size: 15px;">${project.name}</code>
                        <span style="color: #718096; margin-left: 8px; font-size: 12px;">${project.time}</span>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <span style="background: #667eea; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-right: 8px;">TECH: ${project.techStack}</span>
                        <span style="background: #764ba2; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px;">ROLE: ${project.role}</span>
                    </div>
                    <p style="margin: 0; color: #2d3748; line-height: 1.6; font-size: 14px;">${project.description}</p>
                </div>
            `).join('')}
        </div>
        ` : ''}

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
            <div style="background: #f8fafc; padding: 16px; border-radius: 6px;">
                <h3 style="color: var(--primary-color); margin-bottom: 8px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">// EDUCATION</h3>
                <div>
                    <code style="color: #1a365d; font-weight: bold;">${data.school}</code>
                    <div style="color: #4a5568; margin-top: 2px; font-size: 14px;">${data.degree} • ${data.major}</div>
                    <div style="color: #718096; font-size: 12px; margin-top: 2px;">${data.graduation}</div>
                </div>
            </div>
            <div style="background: #f8fafc; padding: 16px; border-radius: 6px;">
                <h3 style="color: var(--primary-color); margin-bottom: 8px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">// SKILLS</h3>
                <div style="color: #2d3748; white-space: pre-line; line-height: 1.4; font-size: 13px; font-family: 'Courier New', monospace;">${data.skills}</div>
            </div>
        </div>
    `;
}

// 初始化模板系统
function initializeTemplateSystem() {
    // 添加模板按钮样式
    const style = document.createElement('style');
    style.textContent = `
        .template-btn {
            padding: 10px 16px;
            border: 1px solid var(--primary-color);
            background: rgba(255,255,255,0.8);
            color: var(--primary-color);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .template-btn:hover {
            background: var(--primary-color);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        .template-btn.active {
            background: var(--primary-color);
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .template-selector-preview {
            animation: fadeInUp 0.6s ease-out;
        }
        
        @keyframes templateSwitch {
            0% { opacity: 0.8; transform: scale(0.98); }
            100% { opacity: 1; transform: scale(1); }
        }
        
        #resume-preview.template-switching {
            animation: templateSwitch 0.4s ease-out;
        }
    `;
    document.head.appendChild(style);
    
    // 绑定模板切换事件
    document.querySelectorAll('.template-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有active状态
            document.querySelectorAll('.template-btn').forEach(b => b.classList.remove('active'));
            
            // 添加active状态到当前按钮
            this.classList.add('active');
            
            // 获取选择的模板
            const template = this.dataset.template;
            localStorage.setItem('selectedTemplate', template);
            
            // 添加切换动画
            const preview = document.getElementById('resume-preview');
            if (preview) {
                preview.classList.add('template-switching');
                setTimeout(() => {
                    preview.classList.remove('template-switching');
                }, 400);
            }
            
            // 更新预览
            updatePreview();
            
            // 显示提示消息
            const templateNames = {
                'modern': '现代简约',
                'classic': '商务经典', 
                'tech': '专业技术'
            };
            showMessage(`已切换到${templateNames[template]}模板`, 'success');
        });
    });
    
    // 设置默认模板
    const savedTemplate = localStorage.getItem('selectedTemplate') || 'modern';
    const defaultBtn = document.querySelector(`[data-template="${savedTemplate}"]`);
    if (defaultBtn) {
        defaultBtn.classList.add('active');
    }
}

// 初始化AI分析
function initializeAIAnalysis() {
    // AI分析功能将在后续实现
    console.log('AI分析系统已初始化');
}

// 执行AI分析
function performAIAnalysis(data, experiences, projects) {
    // 模拟AI分析
    setTimeout(() => {
        const analysis = analyzeResume(data, experiences, projects);
        updateAIFeedback(analysis);
    }, 500);
}

// 简历分析算法
function analyzeResume(data, experiences, projects) {
    let score = 0;
    const feedback = [];
    
    // 基本信息完整性 (20分)
    if (data.name && data.phone && data.email && data.position) {
        score += 20;
    } else {
        feedback.push('请完善基本联系信息');
    }
    
    // 个人简介质量 (15分)
    if (data.summary) {
        if (data.summary.length > 50) {
            score += 15;
        } else {
            score += 8;
            feedback.push('个人简介可以更详细，建议包含核心技能和经验');
        }
    } else {
        feedback.push('建议添加个人简介，突出您的核心竞争力');
    }
    
    // 工作经历 (25分)
    if (experiences.length > 0) {
        score += Math.min(experiences.length * 8, 25);
        experiences.forEach(exp => {
            if (!exp.description || exp.description.length < 30) {
                feedback.push(`${exp.company}的工作描述过于简单，建议添加具体成果`);
            }
        });
    } else {
        feedback.push('建议添加工作经历，展示您的专业经验');
    }
    
    // 项目经验 (20分)
    if (projects.length > 0) {
        score += Math.min(projects.length * 10, 20);
        projects.forEach(project => {
            if (!project.techStack) {
                feedback.push(`项目"${project.name}"建议添加技术栈信息`);
            }
        });
    } else {
        feedback.push('建议添加项目经验，展示您的实际能力');
    }
    
    // 教育背景 (10分)
    if (data.school && data.major) {
        score += 10;
    } else {
        feedback.push('请完善教育背景信息');
    }
    
    // 技能专长 (10分)
    if (data.skills) {
        score += 10;
    } else {
        feedback.push('建议添加技能专长，提升竞争力');
    }
    
    return {
        score: Math.min(score, 100),
        feedback: feedback,
        level: score >= 80 ? '优秀' : score >= 60 ? '良好' : '需改进'
    };
}

// 更新AI反馈
function updateAIFeedback(analysis) {
    const scoreElement = document.querySelector('.page-header .info-badge');
    if (scoreElement) {
        scoreElement.textContent = `评分: ${analysis.score}分`;
        scoreElement.className = `info-badge ${analysis.score >= 80 ? 'success' : analysis.score >= 60 ? 'warning' : 'error'}`;
    }
    
    const feedbackContainer = document.querySelector('.ai-feedback ul');
    if (feedbackContainer) {
        feedbackContainer.innerHTML = analysis.feedback.map(item => `<li>${item}</li>`).join('');
    }
}

// 初始化PDF导出
function initializePDFExport() {
    // 添加jsPDF库
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
    document.head.appendChild(script);
    
    // 添加html2canvas库
    const html2canvasScript = document.createElement('script');
    html2canvasScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
    document.head.appendChild(html2canvasScript);
}

// 导出PDF
function exportToPDF() {
    if (typeof window.jsPDF === 'undefined' || typeof html2canvas === 'undefined') {
        showMessage('PDF导出功能加载中，请稍后重试', 'warning');
        return;
    }
    
    const preview = document.getElementById('resume-preview');
    if (!preview) return;
    
    showMessage('正在生成PDF...', 'info');
    
    html2canvas(preview, {
        scale: 2,
        useCORS: true,
        allowTaint: true
    }).then(canvas => {
        const { jsPDF } = window.jsPDF;
        const pdf = new jsPDF('p', 'mm', 'a4');
        
        const imgWidth = 210;
        const pageHeight = 295;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let heightLeft = imgHeight;
        
        const imgData = canvas.toDataURL('image/png');
        let position = 0;
        
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
        
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            pdf.addPage();
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        
        const fileName = `简历_${document.querySelector('[name="name"]')?.value || '未命名'}_${new Date().toISOString().split('T')[0]}.pdf`;
        pdf.save(fileName);
        
        showMessage('PDF导出成功！', 'success');
    }).catch(error => {
        console.error('PDF导出失败:', error);
        showMessage('PDF导出失败，请重试', 'error');
    });
}

// AI优化功能
function performAIOptimization() {
    showMessage('正在进行AI智能优化...', 'info');
    
    // 模拟AI优化过程
    setTimeout(() => {
        const optimizations = [
            {
                field: 'summary',
                suggestion: '您的个人简介已优化，更突出了核心技能和经验亮点。',
                originalText: document.querySelector('[name="summary"]')?.value || '',
                optimizedText: generateOptimizedSummary()
            },
            {
                field: 'description',
                suggestion: '工作描述已优化，增加了量化成果和关键成就。',
                improvements: ['添加具体数据支撑', '突出核心贡献', '使用动作词汇']
            }
        ];
        
        applyAIOptimizations(optimizations);
        showMessage('AI优化完成！简历质量得到提升', 'success');
        
        // 重新分析和更新预览
        updatePreview();
    }, 2000);
}

// 生成优化的个人简介
function generateOptimizedSummary() {
    const currentSummary = document.querySelector('[name="summary"]')?.value || '';
    const name = document.querySelector('[name="name"]')?.value || '';
    const position = document.querySelector('[name="position"]')?.value || '';
    
    // 简单的AI优化逻辑
    if (currentSummary.length < 50) {
        return `拥有丰富${position}经验的专业人才，具备扎实的技术功底和优秀的问题解决能力。在项目开发和团队协作方面表现出色，致力于通过技术创新推动业务发展，为公司创造价值。`;
    } else {
        // 对现有简介进行优化
        return currentSummary
            .replace(/我/g, '本人')
            .replace(/。/g, '，具备强大的学习能力和适应性。')
            .replace(/，具备强大的学习能力和适应性。$/, '，致力于为企业创造更大价值。');
    }
}

// 应用AI优化建议
function applyAIOptimizations(optimizations) {
    optimizations.forEach(opt => {
        if (opt.field === 'summary' && opt.optimizedText) {
            const summaryField = document.querySelector('[name="summary"]');
            if (summaryField) {
                summaryField.value = opt.optimizedText;
                
                // 高亮显示已优化的字段
                summaryField.style.border = '2px solid var(--success-color)';
                summaryField.style.backgroundColor = 'rgba(16, 185, 129, 0.1)';
                
                setTimeout(() => {
                    summaryField.style.border = '';
                    summaryField.style.backgroundColor = '';
                }, 3000);
            }
        }
    });
}

// 主题系统相关函数
function initializeTheme() {
    // 从本地存储加载主题设置
    const savedTheme = localStorage.getItem('interview-theme') || 'dark';
    applyTheme(savedTheme);
    
    // 更新主题切换按钮图标
    updateThemeIcon(savedTheme);
}

function toggleTheme() {
    const currentTheme = document.documentElement.getAttribute('data-theme') || 'dark';
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    
    applyTheme(newTheme);
    updateThemeIcon(newTheme);
    
    // 保存主题设置到本地存储
    localStorage.setItem('interview-theme', newTheme);
    
    // 显示切换提示
    showMessage(`已切换到${newTheme === 'light' ? '浅色' : '深色'}主题`, 'success');
}

function applyTheme(theme) {
    if (theme === 'light') {
        document.documentElement.setAttribute('data-theme', 'light');
    } else {
        document.documentElement.removeAttribute('data-theme');
    }
}

function updateThemeIcon(theme) {
    const themeToggle = document.querySelector('.theme-toggle .icon');
    if (themeToggle) {
        themeToggle.textContent = theme === 'light' ? '🌙' : '☀️';
    }
}

// 工具函数
const utils = {
    // 格式化日期
    formatDate(date) {
        return new Date(date).toLocaleDateString('zh-CN');
    },
    
    // 格式化数字
    formatNumber(num) {
        return num.toLocaleString();
    },
    
    // 生成UUID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substring(2);
    },
    
    // 深拷贝
    deepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }
}; 